{#
 # ---------------------------------------------------------------------
 #
 # GLPI - Gestionnaire Libre de Parc Informatique
 #
 # http://glpi-project.org
 #
 # @copyright 2015-2025 Teclib' and contributors.
 # @licence   https://www.gnu.org/licenses/gpl-3.0.html
 #
 # ---------------------------------------------------------------------
 #
 # LICENSE
 #
 # This file is part of GLPI.
 #
 # This program is free software: you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation, either version 3 of the License, or
 # (at your option) any later version.
 #
 # This program is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.
 #
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
 #
 # ---------------------------------------------------------------------
 #}

<div class="ms-2">
    <button
        class="btn btn-primary me-1 {{ show_save ? "" : "d-none" }}"
        type="submit"
        name="save_filters"
    >
        <i class="ti ti-device-floppy"></i>
        <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
        <span class="d-none d-sm-block">{{ __("Save") }}</span>
    </button>

    <button
        class="btn btn-outline-danger me-1 {{ show_delete ? "" : "d-none" }}"
        name="delete_filters"
    >
        <i class="ti ti-trash"></i>
        <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
        <span class="d-none d-sm-block">{{ __("Delete") }}</span>
    </button>
</div>

<script type="module">
    function showLoading(btn) {
        btn.find('i').addClass('d-none');
        btn.find('.spinner-border').removeClass('d-none');
        // Disable this and sibling buttons
        btn.prop('disabled', true);
        btn.siblings('button').prop('disabled', true);
    }

    function hideLoading(btn) {
        btn.find('i').removeClass('d-none');
        btn.find('.spinner-border').addClass('d-none');
        // Enable this and sibling buttons
        btn.prop('disabled', false);
        btn.siblings('button').prop('disabled', false);
    }

    // Save action
    $("button[name='save_filters']").on("click", (e) => {
        // Prevent form submit
        e.preventDefault();

        const btn = $(e.currentTarget);

        // Find form
        const form = btn.closest('form');

        showLoading(btn);

        // Save results
        const form_data = new FormData(form[0]);

        // Add references to parent item, must be prefixed by "item_" because
        // "itemtype" will already be set by the search's form
        form_data.append('item_itemtype', "{{ itemtype }}");
        form_data.append('item_items_id', {{ items_id }});

        // Endpoint
        form_data.append('action', "save_filter");

        // Send data to backend
        $.ajax({
            type: "POST",
            url: CFG_GLPI.root_doc + "/ajax/criteria_filter.php",
            data: form_data,
            processData: false, // Needed when using FormData object
            contentType: false, // Needed when using FormData object
        }).done(function() {
            glpi_toast_info("{{ __("Filter saved") }}");
    {% if delete_action_id is defined %}
            // Show delete button if it wasn't already enabled
            $("#{{ delete_action_id }}").removeClass('d-none');
    {% endif %}

            // Add badge to menu to hint that a filter have been set
            const tab = $("a.nav-link[href*='CriteriaFilter']");
            if (tab.find('span.badge').length == 0) {
                tab.append('<span class="badge">1</span>');
            }
        }).fail(function() {
            glpi_toast_error("{{ __("Unable to save filter") }}");
        }).always(function() {
            hideLoading(btn);
        });

        // Hide preview since its content may not match the saved value
        $("#criteria_filter_preview").addClass("d-none");
    });

    // Delete action
    $("button[name='delete_filters']").on("click", (e) => {
        // Prevent form submit
        e.preventDefault();

        const btn = $(e.currentTarget);
        showLoading(btn);

        $.ajax({
            type: "POST",
            url: CFG_GLPI.root_doc + "/ajax/criteria_filter.php",
            data: {
                'action': 'delete_filter',
                'itemtype': '{{ itemtype }}',
                'items_id': {{ items_id }},
            },
        }).done(function() {
            // Reload page, easiest way to clear search UI
            location.reload();
        }).fail(function() {
            hideLoading(btn);

            glpi_toast_error("{{ __("Failed to delete filter") }}");
        });
    });
</script>
